package com.lglbc.day18.filter;

import com.alibaba.fastjson.JSON;
import com.lglbc.day18.config.JwtTokenUtil;
import com.lglbc.day18.entity.AccessToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.thymeleaf.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
@WebFilter(filterName = "TokenLoginFilter", urlPatterns = "/*")//先全部拦截
public class TokenLoginFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException, IOException {

        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            filterChain.doFilter(request, response);
            return;
        }
        AccessToken accessToken = JwtTokenUtil.verifyTokenByRSA(authorization);
        if (Objects.isNull(accessToken)) {
            filterChain.doFilter(request, response);
            return;
        }
        //已登录，获取用户信息，进行授权
        List<SimpleGrantedAuthority> authorities = accessToken.getAuthorities().stream().map(permission ->
                new SimpleGrantedAuthority(permission)
        ).collect(Collectors.toList());
        UsernamePasswordAuthenticationToken token =
                new UsernamePasswordAuthenticationToken(accessToken.getUsername(), null, authorities);
        SecurityContextHolder.getContext().setAuthentication(token);
        System.out.println("SecurityContextHolder信息：" + JSON.toJSONString(SecurityContextHolder.getContext()));
        filterChain.doFilter(request, response);
    }
}
